package me.zhengjie.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/**
 * Lv-smart数据源配置
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryLvsmart",
        transactionManagerRef = "transactionManagerLvsmart",
        basePackages = {"me.zhengjie.modules.*.repositorySmart"})
public class LvsmartDataSourceConfig {

    @Autowired
    @Qualifier("lvsmartDataSource")
    private DataSource lvsmartDataSource;

    @Resource
    private JpaProperties jpaProperties;

    @Resource
    private HibernateProperties hibernateProperties;

    @Bean(name = "entityManagerLvsmart")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryLvsmart(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactoryLvsmart")    //实体工厂
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryLvsmart(EntityManagerFactoryBuilder builder) {

        return builder.dataSource(lvsmartDataSource)
                .properties(getHibernateProperties())
                .packages("me.zhengjie.modules.*.domainSmart")     //实体类所在位置
                .persistenceUnit("lvsmartPersistenceUnit")
                .build();
    }

    @Bean(name = "transactionManagerLvsmart")
    public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryLvsmart(builder).getObject());
    }

    private Map<String, Object> getHibernateProperties() {
        return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
    }

}